import Vue from 'vue'
import store from '../store/index.js'

import config  from '../http.config.js'
import {alert} from './alert.js'

export class HTTP {
  async request({ url, method = "GET", data = {}, http = config.httpUrl }) { // http请求
		try{
			await this._checkSession()
			return this._request({ url, method , data , http})
		}catch(e){
			await this._login()
			return this._request({ url, method , data, http })
		}
  }

  _request({ url, method, data, http }) {
    uni.showNavigationBarLoading()
    return new Promise((resolve, reject) => {
      uni.request({
        url: http + url,
        method,
        data,
        header: this._setHttpHerder(),
        success: res => {
          uni.hideNavigationBarLoading() // 隐藏导航条加载动画
          if (res.statusCode === 200 || res.statusCode === 201) {
						if(res.data.errnu == 0) {
							resolve(res.data.data)
						} else if (res.data.errnu == 707) {
							this._show_error("您当前未登录，请先进行登录哦～", "登录", true);
							reject("707");
						} else {
							this._show_error(res.data.error);
						}
          } else if (res.statusCode === 404) {
            this._show_error(res.data.error ? res.data.error : '请求地址不存在');
          } else {
						console.log(res)
						this._show_error(res.data.error);
          }
        },
        fail: err => {
					this._show_error(res.data.error);
        }
      })
    })
  }
	
	_checkSession() {
		let userInfo = uni.getStorageSync('userData')
		return new Promise((resolve, reject)=>{
			uni.checkSession({
				success:(res) => {
					if(res.errMsg == "checkSession:ok"){
						resolve()
					}
				},
				fail: () => reject()
			})
		})
	}
	
  _login() {
    return new Promise((resolve, reject)=>{
      uni.login({
        success:(res)=>{
          if(res.code) {
            uni.request({
              url: config.httpUrl + 'init',
              data: { code: res.code },
              method: 'GET', 
              success:(session)=>{
                uni.setStorageSync('userData', session.data.data);
								if(session.data.data.userinfo === false || !session.data.data.login_token) {
									store.commit('setUserAccredit', true)
								} else {
									store.commit('setUserAccredit', false)
								}
								store.commit('setUserInfo', {
									nickName: session.data.nickname,
									avatarUrl: session.data.avatar,
								})
                resolve(session.data);
              }
            })
          }
        },
        fail:()=> {
          reject()
        }
      })
    })
  }

  uploadFile(list) {
    return new Promise((resolve, reject) => {
      this._uploadFile({
        list
      }, (res) => res === false ? reject('上传图片失败') : resolve(res))
    })
  }

  _uploadFile(data, cb) {
    let i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    uni.uploadFile({
      url: config.httpUrl + 'stock/upload',
      filePath: Boolean(data.list[i].img) ? data.list[i].img : data.list[i],
      name: 'file',
      header: this._setHttpHerder(),
      formData: {
        type: 'image'
      },
      success: (res) => {
        if (res.statusCode === 200 || res.statusCode === 201) {
          success++;
          if (data.list[i].img) {
            data.list[i].img = JSON.parse(res.data).data.path;
          } else {
            data.list[i] = JSON.parse(res.data).data.path;
          }
		  
		   i++
          if (i == data.list.length) { //当图片传完时，停止调用
            // 图片上传完进行签到
            return typeof cb == "function" && cb(data.list);
          } else { //若图片还没有传完，则继续调用函数
            data.i = i
            data.success = success
            data.fail = fail
            this._uploadFile(data, cb)
          }
        } else {
          return typeof cb == "function" && cb(false)
        }
      },
      fail: (res) => {
        fail++;
        return typeof cb == "function" && cb(false)
      }
    })
  }

  _setHttpHerder(){ // 设置请求头部信息
    let userInfo = uni.getStorageSync('userData')
    let header = {
      'content-type': 'application/json'
    }
    if(userInfo) {
      header.authToken = userInfo.auth_token;
			header.loginToken = userInfo.login_token || "";
    }
    return header
  }

  _show_error(code, title="提示", btn=false) {
		uni.hideLoading()
		let content = code || '抱歉，发生了一个错误'
		alert(content, title, btn).then(()=>{
			setTimeout(()=> {
				if(title=="登录") {
					uni.switchTab({
						url: "/pages/tab/my/my"
					})
				} else {
					uni.navigateBack({
						delta: 1
					})
				}
			}, 300)
		})
  }
}